<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>选择体检日期</p>
      <div></div>
    </header>
    <div class="top-ban"></div>

    <section>
      <div class="date-box">
        <i class="fa fa-caret-left" @click="subtractMonth"></i>
        <p>{{ year + "年" + month + "月" }}</p>
        <i class="fa fa-caret-right" @click="addMonth"></i>
      </div>
      <table>
        <tr>
          <th>日</th>
          <th>一</th>
          <th>二</th>
          <th>三</th>
          <th>四</th>
          <th>五</th>
          <th>六</th>
        </tr>
      </table>
      <ul>
        <li v-for="(calendar, index) in calendarArr" :key="index">
          <p :class="{
            fontcolor: calendar?.remainder != null && calendar?.remainder !== 0,
            pselect: calendar?.selectDay === 1,
          }" @click="selectDay(index)"
            :style="{ cursor: calendar?.remainder && calendar?.remainder > 0 ? 'pointer' : 'default' }">
            {{ calendar?.day || '' }}
          </p>
          <p>
            {{ calendar?.remainder != null && calendar?.remainder !== 0 ? "余" + calendar.remainder : "" }}
          </p>
        </li>
      </ul>
    </section>

    <div class="bottom-btn">
      <div></div>
      <div @click="toConfirmOrder">下一步</div>
    </div>

    <div class="bottom-ban"></div>
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/Footer.vue";
import { reactive, toRefs, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";

// 模拟页脚组件（如果实际项目中有可删除此部分）
const MockFooter = {
  template: `<div class="footer" style="width:100%;height:14.2vw;background:#fff;position:fixed;bottom:0;display:flex;justify-content:center;align-items:center;font-size:3.5vw;color:#666;">
    底部导航区域
  </div>`
};

export default {
  components: {
    Footer: Footer || MockFooter  // 兼容无Footer组件的情况
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const curDate = new Date();

    const state = reactive({
      hpId: route.query.hpId,
      smId: route.query.smId,
      year: curDate.getFullYear(),
      month: curDate.getMonth() + 1,
      calendarArr: [],
      selectDay: "", // 用户选择的预约日期
    });

    // 生成模拟日历数据
    const generateMockCalendar = () => {
      const daysInMonth = new Date(state.year, state.month, 0).getDate();
      const firstDayOfMonth = new Date(state.year, state.month - 1, 1).getDay();
      const calendar = [];

      // 填充月初空白
      for (let i = 0; i < firstDayOfMonth; i++) {
        calendar.push({});
      }

      // 生成当月日期数据
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(state.year, state.month - 1, day);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        // 模拟剩余名额：过去的日期不可选，未来日期随机1-20个名额
        let remainder = null;
        if (date >= today) {
          remainder = Math.floor(Math.random() * 20) + 1;
        }

        calendar.push({
          ymd: `${state.year}${String(state.month).padStart(2, '0')}${String(day).padStart(2, '0')}`,
          day,
          remainder,
          selectDay: 0
        });
      }

      // 确保日历总天数是7的倍数（填满整周）
      const totalDays = calendar.length;
      const fillDays = 7 - (totalDays % 7);
      if (fillDays < 7) {
        for (let i = 0; i < fillDays; i++) {
          calendar.push({});
        }
      }

      return calendar;
    };

    // 获取日历数据（前端模拟）
    const getCalendar = () => {
      const mockData = generateMockCalendar();
      // 处理选中状态
      state.calendarArr = mockData.map(item => {
        if (!item.ymd) return item;
        return {
          ...item,
          selectDay: item.ymd === state.selectDay ? 1 : 0
        };
      });
    };

    // 上一个月
    const subtractMonth = () => {
      if (state.month > 1) {
        state.month--;
      } else {
        state.year--;
        state.month = 12;
      }
      getCalendar();
    };

    // 下一个月
    const addMonth = () => {
      if (state.month < 12) {
        state.month++;
      } else {
        state.year++;
        state.month = 1;
      }
      getCalendar();
    };

    // 选择日期
    const selectDay = (index) => {
      const calendar = state.calendarArr[index];
      // 验证是否为可预约日期
      if (!calendar || calendar.remainder == null || calendar.remainder === 0) {
        return;
      }

      // 清空所有选中状态
      state.calendarArr = state.calendarArr.map((item, i) => ({
        ...item,
        selectDay: i === index ? 1 : 0
      }));

      state.selectDay = calendar.ymd;
    };

    // 前往确认订单
    function toConfirmOrder() {
      if (state.selectDay == '') {
        alert('请选择体检预约日期！');
        return;
      }
      router.push({ path: '/confirmOrder', query: { hpId: state.hpId, smId: state.smId, selectDay: state.selectDay, flag: 1 } });
    }

    // 返回上一页
    const goBack = () => {
      router.back();
    };

    // 组件挂载时生成日历数据
    onMounted(() => {
      getCalendar();
    });

    return {
      ...toRefs(state),
      subtractMonth,
      addMonth,
      selectDay,
      toConfirmOrder,
      goBack
    };
  }
};
</script>

<style scoped>
/*********************** 总容器 ***********************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f9f9f9;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/*********************** header ***********************/
header {
  width: 100%;
  height: 15.7vw;
  background-color: #fff;
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 3.6vw;
  z-index: 10;
  margin: 0;
}

header .fa {
  font-size: 8vw;
  cursor: pointer;
  color: #333;
}

header p {
  margin: 0;
  font-size: 4.5vw;
  color: #333;
  font-weight: 600;
}

/*********************** common样式 ***********************/
.top-ban {
  width: 100%;
  height: 15.7vw;
}

.bottom-ban {
  width: 100%;
  height: 14.2vw;
}

/*********************** section ***********************/
section {
  width: 82vw;
  margin: 0 auto;
  padding-top: 12vw;
}

section .date-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 4.5vw;
  font-weight: 600;
  margin-bottom: 2vw;
}

section .date-box p {
  color: #000;
  margin: 0;
}

section .date-box i {
  color: #999;
  user-select: none;
  cursor: pointer;
  font-size: 5vw;
}

section table {
  width: 100%;
  font-size: 3.8vw;
  border-collapse: collapse;
}

section table tr th {
  text-align: center;
  font-weight: 600;
  line-height: 12vw;
  color: #666;
}

section ul {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  padding: 0;
  margin: 0;
}

section ul li {
  width: 14.28%;
  height: 12vw;
  font-weight: 600;
  color: #999;
  box-sizing: border-box;
}

section ul li p:first-child {
  width: 6vw;
  height: 6vw;
  margin: 0 auto;
  border-radius: 3vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 4.2vw;
  user-select: none;
}

section ul li p:last-child {
  font-size: 3vw;
  font-weight: 300;
  text-align: center;
  user-select: none;
  margin: 1vw 0 0 0;
}

.fontcolor {
  color: #333;
}

.pselect {
  background-color: #fb902b;
  color: #fff;
}

/*********************** bottom-btn ***********************/
.bottom-btn {
  width: 100%;
  height: 12vw;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 14.2vw;
  display: flex;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.bottom-btn div:first-child {
  flex: 2;
}

.bottom-btn div:last-child {
  flex: 1;
  background-color: #117c94;
  text-align: center;
  line-height: 12vw;
  font-size: 5vw;
  color: #fff;
  user-select: none;
  cursor: pointer;
}

/* 引入Font Awesome图标 */
@import url("https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css");
</style>